package top.xiangqifu.springboot2.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import top.xiangqifu.springboot2.user.base.BasePageResult;
import top.xiangqifu.springboot2.user.base.BaseResult;
import top.xiangqifu.springboot2.user.base.PageBean;
import top.xiangqifu.springboot2.user.dao.TbUserDAO;
import top.xiangqifu.springboot2.user.dao.TbUserInfoDAO;
import top.xiangqifu.springboot2.user.entity.AuthInfo;
import top.xiangqifu.springboot2.user.entity.TbUser;
import top.xiangqifu.springboot2.user.entity.TbUserInfo;
import top.xiangqifu.springboot2.user.service.AuthService;
import top.xiangqifu.springboot2.user.service.UserInfoService;
import top.xiangqifu.springboot2.user.utils.AuthInfoUtils;
import top.xiangqifu.springboot2.user.vo.UserInfo;

import java.util.List;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserInfoServiceImpl implements UserInfoService {
        private final AuthService authService;
        private final TbUserDAO tbUserDAO;
        private final TbUserInfoDAO tbUserInfoDAO;

    @Override
    public BasePageResult<List<TbUser>> queryAll(PageBean pageBean, TbUser users){
        QueryWrapper<TbUser> queryUser = new QueryWrapper<>();
        queryUser.select("uid", "username", "deleted","role");
        queryUser.like(StringUtils.hasText(users.getUsername()), "username", users.getUsername());

        IPage<TbUser> page = pageBean.toPage(TbUser.class);
        tbUserDAO.selectPage(page, queryUser);
        page.getRecords().forEach(user -> {
            UserInfo userInfo1 = authService.queryById(user.getUid());
            user.setUserInfo(userInfo1.InfoRole());
        });

        pageBean.buildPageInfo(page);
        return BasePageResult.ok(pageBean, page.getRecords());
    }

    @Override
    public BaseResult updateInfo(TbUserInfo tbUserInfo){
        AuthInfo authInfo= AuthInfoUtils.authInfo();
        tbUserInfo.setUid(authInfo.getUid());
        int i=tbUserInfoDAO.updateById(tbUserInfo);
        if (i!=1){
            return BaseResult.fail("附加信息添加失败");
        }
        return BaseResult.ok("附加信息添加成功");
    }
    }

